<template>
  <div>
    <div class="box-border p-12px">
      <el-form
        ref="formRef"
        :rules="rules"
        :disabled="isDetail"
        :model="submitForm"
        label-width="100px"
        class="mt-12px"
      >
        <div>
          <SubTitle title="策略基本信息" />
          <el-form-item label="策略名称：" required prop="strategyName">
            <ns-input v-model="submitForm.strategyName" clearable placeholder="请输入策略名称" />
          </el-form-item>
          <el-form-item label="策略描述：" prop="strategyDesc">
            <ns-input v-model="submitForm.strategyDesc" clearable placeholder="请输入策略描述" />
          </el-form-item>
        </div>
        <div class="mt-16px">
          <SubTitle title="策略基本信息" />
          <el-card shadow="never">
            <!-- <el-tabs v-model="tabName" class="demo-tabs"> -->
            <!-- <el-tab-pane
                :label="tabNameList[tabKey]"
                :name="tabKey"
                v-for="(tab, tabKey) in strategyRule"
                :key="tabKey"
              > -->
            <el-card
              class="mb-12px"
              shadow="never"
              v-for="(rules, index) in strategyRule['file']"
              :key="index"
            >
              <div class="flex items-center">
                规则{{ index + 1 }}
                <div class="ml-auto mr-12px font-size-14px">
                  启用状态：
                  <el-switch v-model="rules.enable" />
                </div>
                <el-icon
                  class="cursor-pointer"
                  v-if="strategyRule['file'].length > 1 && !isDetail"
                  @click="delRules('file', index)"
                  ><Close
                /></el-icon>
              </div>
              <el-table :data="rules.conditionDTOS" style="width: 100%">
                <el-table-column label="序号" type="index" width="100" />
                <el-table-column label="条件对象">
                  <template #default="scope">
                    <el-select
                      v-model="scope.row.conditionObject"
                      @change="scope.row.codeType = ''"
                      placeholder="请选择条件对象"
                    >
                      <el-option
                        v-for="(ite, i) in conditionList"
                        :key="i"
                        :label="ite.label"
                        :value="ite.value"
                        v-show="ite.type == 'file'"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="条件类型">
                  <template #default="scope">
                    <el-select v-model="scope.row.codeType" placeholder="请选择条件类型">
                      <template v-for="(ite, i) in conditionTypeList" :key="i">
                        <el-option
                          :label="ite.label"
                          :value="ite.value"
                          v-show="
                            scope.row.conditionObject &&
                            (ite.value == 'REGEX' || scope.row.conditionObject == 'fileContent')
                          "
                        />
                      </template>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="表达式">
                  <template #default="scope">
                    <ns-input
                      v-model="scope.row.regexContent.value"
                      v-if="scope.row.codeType !== 'SERVERLESS'"
                      placeholder="请输入表达式"
                      maxlength="500"
                    />
                    <el-select v-model="scope.row.serverlessContentId" v-else>
                      <el-option
                        v-for="(algorithm, algorithmIndex) in algorithmList"
                        :key="algorithmIndex"
                        :label="algorithm.algorithmName"
                        :value="algorithm.id"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="最少次数">
                  <template #default="scope">
                    <ns-input v-model.number="scope.row.keyWord" />
                  </template>
                </el-table-column> -->
                <el-table-column label="操作" v-if="!isDetail" width="100px">
                  <template #default="scope">
                    <el-button
                      :icon="Minus"
                      size="small"
                      circle
                      v-if="scope.$index !== 0"
                      class="ml-12px"
                      @click="delRow('file', index, scope.$index)"
                    />
                    <el-button
                      :icon="Plus"
                      size="small"
                      circle
                      class="ml-12px"
                      v-if="rules.conditionDTOS.length === scope.$index + 1"
                      @click="addRow('file', index, scope.$index)"
                    />
                  </template>
                </el-table-column>
              </el-table>
              <el-form-item label="条件关系：">
                <el-radio-group
                  v-model="rules.logicOperation"
                  @change="(v) => handleChange(v, rules)"
                >
                  <el-radio label="or">全部为或</el-radio>
                  <el-radio label="and">全部为且</el-radio>
                  <!-- <el-radio label="not">全部为非</el-radio> -->
                </el-radio-group>
              </el-form-item>
              <!-- <el-form-item m label="最少数量：" v-if="rules.logicOperation == 'or'">
                <ns-input style="width: 230px" v-model="rules.minCount" />
              </el-form-item> -->
            </el-card>
            <el-button @click="addRules('file')" v-if="!isDetail">新增规则</el-button>
            <!-- </el-tab-pane> -->
            <!-- </el-tabs> -->
          </el-card>
        </div>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="confirm" v-if="!isDetail">确定</el-button>
      <el-button @click="closeOutDrawer">{{ isDetail ? '关闭' : '取消' }}</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { Plus, Minus, Close } from '@element-plus/icons-vue'
import { strategyCreate, strategyUpdate } from '@/api/strategyManage/strategy/index'
import { algorithmPage } from '@/api/strategyManage/algorithm/index'
import SubTitle from '@/components/SubTitle/index.vue'

const message = useMessage() // 消息弹窗
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})

const tabName = ref('file')
const tabNameList = {
  column: '字段识别规则',
  table: '表识别规则',
  file: '文件识别规则'
}

const formRef = ref()
const submitForm = ref({
  strategyName: '',
  strategyDesc: ''
})
const rules = {
  strategyName: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }]
  // strategyDesc: [{ required: true, message: '策略描述不能为空', trigger: 'blur' }]
}

const conditionList = [
  {
    label: '字段名称',
    value: 'columnName',
    type: 'column'
  },
  {
    label: '字段描述',
    value: 'columnComment',
    type: 'column'
  },
  {
    label: '字段内容',
    value: 'columnContent',
    type: 'column'
  },
  {
    label: '表名称',
    value: 'tableName',
    type: 'table'
  },
  {
    label: '表描述',
    value: 'tableComment',
    type: 'table'
  },
  {
    label: '文件名称',
    value: 'fileName',
    type: 'file'
  },
  {
    label: '文件内容',
    value: 'fileContent',
    type: 'file'
  },
  {
    label: '文件扩展名',
    value: 'fileSuffix',
    type: 'file'
  }
]

const conditionTypeList = [
  {
    label: '正则',
    value: 'REGEX'
  },
  // {
  //   label: '识别算法引用',
  //   value: 'SERVERLESS'
  // },
  {
    label: '包含',
    value: 'INCLUDE'
  }
]

const strategyRule = ref({
  column: [
    {
      id: guid(),
      enable: true,
      conditionDTOS: [
        {
          id: guid(),
          conditionObject: '',
          codeType: '',
          regexContent: {
            value: ''
          },
          serverlessContentId: ''
        }
      ],
      logicOperation: 'or'
    }
  ],
  table: [
    {
      id: guid(),
      enable: true,
      conditionDTOS: [
        {
          id: guid(),
          conditionObject: '',
          codeType: '',
          regexContent: {
            value: ''
          },
          serverlessContentId: ''
        }
      ],
      logicOperation: 'or'
    }
  ],
  file: [
    {
      id: guid(),
      enable: true,
      conditionDTOS: [
        {
          id: guid(),
          conditionObject: '',
          codeType: '',
          regexContent: {
            value: ''
          },
          serverlessContentId: ''
        }
      ],
      logicOperation: 'or'
    }
  ]
})

const addRules = (tabKey) => {
  strategyRule.value[tabKey].push({
    id: guid(),
    enable: true,
    conditionDTOS: [
      {
        id: guid(),
        conditionObject: '',
        codeType: '',
        regexContent: {
          value: ''
        },
        serverlessContentId: ''
      }
    ],
    logicOperation: 'or'
  })
}
const delRules = (tabKey, index) => {
  strategyRule.value[tabKey].splice(index, 1)
}

const addRow = (tabKey, index, rowIndex) => {
  strategyRule.value[tabKey][index].conditionDTOS.push({
    id: guid(),
    conditionObject: '',
    codeType: '',
    regexContent: {
      value: ''
    },
    serverlessContentId: ''
  })
}
const delRow = (tabKey, index, rowIndex) => {
  strategyRule.value[tabKey][index].conditionDTOS.splice(rowIndex, 1)
}

const handleChange = (v, rules) => {
  if (v == 'not') {
    rules.isNot = true
  } else {
    rules.isNot = false
  }
}

const confirm = async () => {
  const apiInterface = props.params.id ? strategyUpdate : strategyCreate
  formRef.value.validate(async (valid) => {
    if (valid) {
      const data = await apiInterface({
        ...submitForm.value,
        strategyRule: strategyRule.value,
        type: 'secondary'
      })
      console.log('data', data)
      if (data) {
        message.success('操作成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    }
  })
}

// 识别算法下拉列表
const algorithmList = ref([])
const getAlgorithm = async () => {
  const data = await algorithmPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  algorithmList.value = data.data
}

// 生成uuid
function guid() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8
    return v.toString(16)
  })
}
const isDetail = computed(() => {
  return props.params.isDetail
})

onMounted(() => {
  getAlgorithm()
  if (props.params.id) {
    submitForm.value = props.params
    if (props.params.strategyRule) {
      const fileConditionDTOS = strategyRule.value.file[0].conditionDTOS
      strategyRule.value = JSON.parse(props.params.strategyRule)
      strategyRule.value?.file?.map((item) => {
        item.conditionDTOS = item.conditionDTOS.length == 0 ? fileConditionDTOS : item.conditionDTOS
      })
    }
  }
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
